/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Client.java - JMX client that interacts with the JMX agent. It gets
 * attributes and performs operations on the Hello MBean and the QueueSampler
 * MXBean example. It also listens for Hello MBean notifications.
 */

package jmx;

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

import javax.management.AttributeChangeNotification;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import jmx.standardmbean.TomcatServerControllerMBean;
import sample.Util;

public class JMXClient {

	/**
	 * Inner class that will handle the notifications.
	 */

	public static void main(String[] args) throws Exception {
		// Create an RMI connector client and
		// connect it to the RMI connector server
		//
		Util.echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server");
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
		JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
		ClientListener listener = new ClientListener();
		Util.echo("\nGet an MBeanServerConnection");
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		Util.echo("\nDomains:");
		String domains[] = mbsc.getDomains();
		Arrays.sort(domains);
		for (String domain : domains) {
			Util.echo("\tDomain = " + domain);
		}
		Util.echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());
		Util.echo("\nMBean count = " + mbsc.getMBeanCount());
		Util.echo("\nQuery MBeanServer MBeans:");
		Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
		for (ObjectName name : names) {
			Util.echo("\tObjectName = " + name);
		}

		ObjectName mbeanName = new ObjectName("com.example:type=TomcatServerController");
		TomcatServerControllerMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, TomcatServerControllerMBean.class,
				true);
		mbeanProxy.isServerRunning();
		mbsc.addNotificationListener(mbeanName, listener, null, null);

		Thread.sleep(Long.MAX_VALUE);
		Util.waitForEnterPressed("Waiting for notification...");
		Util.echo("\nClosing the connection to the server");
		jmxc.close();
	}

	public static class ClientListener implements NotificationListener {
		public void handleNotification(Notification notification, Object handback) {
			Util.echo("\n##########################");
			Util.echo("\nReceived notification:");
			Util.echo("\tClassName: " + notification.getClass().getName());
			Util.echo("\tSource: " + notification.getSource());
			Util.echo("\tType: " + notification.getType());
			Util.echo("\tMessage: " + notification.getMessage());
			if (notification instanceof AttributeChangeNotification) {
				AttributeChangeNotification acn = (AttributeChangeNotification) notification;
				Util.echo("\tAttributeName: " + acn.getAttributeName());
				Util.echo("\tAttributeType: " + acn.getAttributeType());
				Util.echo("\tNewValue: " + acn.getNewValue());
				Util.echo("\tOldValue: " + acn.getOldValue());
				Util.waitForEnterPressed("Client listener blocking Start");
				try {
					Thread.sleep(Long.MAX_VALUE);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			Util.waitForEnterPressed("Client listener blocking End");
		}
	}

}
